package gang.com.downloader;

import android.content.Context;
import android.content.Intent;

/**
 * Created by xiaogangzai on 2017/11/4.
 * 接收用户的action，例如一些暂停、继续等的命令，经过一系列的处理然后交给我们的DownloadService
 */

public class DownloadManager {
    //所有的action都需要用到这个DownloadManager，想到单例模式
    private static DownloadManager mIntance;
    private final Context context;

    private DownloadManager(Context context) {
        this.context = context;
    }

    public static  synchronized DownloadManager getmIntance(Context context) {
        if (mIntance == null) {
            mIntance = new DownloadManager(context);
        }
        return mIntance;
    }
   //下载
    public void add(Context context, DownloadEntry entry) {
        //跳转到Service
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(Constants.KEY_DOWNLOAD_ENTRY, entry);
        intent.putExtra(Constants.KEY_DOWNLOAD_ACTION, Constants.KEY_DOWNLOAD_ACTION_ADD);
        context.startActivity(intent);
    }

    //暂停
    public void pause(DownloadEntry entry) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(Constants.KEY_DOWNLOAD_ENTRY, entry);
        intent.putExtra(Constants.KEY_DOWNLOAD_ACTION, Constants.KEY_DOWNLOAD_ACTION_PAUSE);
        context.startService(intent);
    }
    //继续重新开始
    public void resume(DownloadEntry entry) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(Constants.KEY_DOWNLOAD_ENTRY, entry);
        intent.putExtra(Constants.KEY_DOWNLOAD_ACTION, Constants.KEY_DOWNLOAD_ACTION_RESUME);
        context.startService(intent);
    }
    //取消
    public void cancel(DownloadEntry entry) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(Constants.KEY_DOWNLOAD_ENTRY, entry);
        intent.putExtra(Constants.KEY_DOWNLOAD_ACTION, Constants.KEY_DOWNLOAD_ACTION_CANCEL);
        context.startService(intent);
    }

    //被观察者和观察者的订阅
    public void addObserver(DataWatcher watcher)
    {
        DataChanger.getmInstance().addObserver(watcher);
    }
    //解阅
    public void removeObserver(DataWatcher watcher)
    {
        DataChanger.getmInstance().deleteObserver(watcher);
    }
}
